package com.pkutech.carcasher.activity;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.RadioButton;
import android.widget.TextView;

import com.afollestad.materialdialogs.AlertDialogWrapper;
import com.dd.processbutton.iml.ActionProcessButton;
import com.pkutech.carcasher.R;
import com.pkutech.carcasher.bean.AlipayReqsponse;
import com.pkutech.carcasher.bean.BaseResponse;
import com.pkutech.carcasher.bean.GetInvoceInfoResponse;
import com.pkutech.carcasher.bean.PayFeesResponse;
import com.pkutech.carcasher.bean.PrintRequest;
import com.pkutech.carcasher.db.RealmManager;
import com.pkutech.carcasher.model.HmSelectFormalOrder;
import com.pkutech.carcasher.model.Rate;
import com.pkutech.carcasher.network.SoapApi;
import com.pkutech.carcasher.utils.BussinessUtil;
import com.pkutech.carcasher.utils.DateUtils;
import com.pkutech.carcasher.utils.PayType;
import com.pkutech.carcasher.utils.StringUtils;
import com.pkutech.carcasher.utils.ToastUtil;
import com.zsd.printer.PrinterCtrl;

import butterknife.BindView;
import butterknife.ButterKnife;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by cyy on 2016/6/27.
 */
public class PayFeesActivity extends BaseActivity {
    private static final int SCANNIN_GREQUEST_CODE = 1;
    private static final int SDK_PAY_FLAG = 1;
    String payJson;


    @BindView(R.id.toolbar)
    Toolbar toolbar;

    HmSelectFormalOrder selectFormalOrder;
    @BindView(R.id.parkingNameTxt)
    TextView parkingNameTxt;
    @BindView(R.id.parkingLotTxt)
    TextView parkingLotTxt;
    @BindView(R.id.startTimeTxt)
    TextView startTimeTxt;
    @BindView(R.id.postageTxt)
    TextView postageTxt;
    @BindView(R.id.payoffBtn)
    ActionProcessButton payoffBtn;

    @BindView(R.id.printBtn)
    ActionProcessButton printBtn;

    @BindView(R.id.radio1)
    RadioButton radio1;
    @BindView(R.id.radio2)
    RadioButton radio2;
    @BindView(R.id.radio3)
    RadioButton radio3;

    String orderId;
    String carnum="";
    String starttime="";
    String endtime="";
    String roadname="";
    String carportCode="";
    String realfee="";
    PayFeesResponse payFees = new PayFeesResponse();

    int payType = 0;

    @BindView(R.id.pay_message)
    TextView pay_message;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_payfees);
        ButterKnife.bind(this);
        initToolbar(toolbar);

        selectFormalOrder = (HmSelectFormalOrder) getIntent().getSerializableExtra(PaymentServiceActivity.SELECT_FORMAL_ORDER);
        parkingNameTxt.setText(selectFormalOrder.getRoadid());
        parkingLotTxt.setText(selectFormalOrder.getCarportid());
        startTimeTxt.setText(selectFormalOrder.getStarttime());
        orderId = selectFormalOrder.getCode();
        carnum = selectFormalOrder.getCarnum();
        starttime=selectFormalOrder.getStarttime();
        endtime = selectFormalOrder.getEndtime();
        if (StringUtils.isNullOrEmpty(endtime)){
            endtime= DateUtils.getNow();
        }
        roadname= selectFormalOrder.getRoadid();
        carportCode=selectFormalOrder.getCarportid();
        getPayCondition();
        radio1.setChecked(true);
        radio2.setEnabled(false);

        radio1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                radio2.setChecked(false);
                radio3.setChecked(false);
                radio1.setChecked(isChecked);
                payType = PayType.CRASH_PAY;
            }
        });
        radio2.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                radio1.setChecked(false);
                radio3.setChecked(false);
                radio2.setChecked(isChecked);
                payType = PayType.WE_PAY;
            }
        });
        radio3.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                radio1.setChecked(false);
                radio2.setChecked(false);
                radio3.setChecked(isChecked);
                payType = PayType.ALI_PAY;
            }
        });
    }

    @Override
    protected void initToolbar(Toolbar toolbar){
        setSupportActionBar(toolbar);
        toolbar.setNavigationIcon(R.drawable.ic_arrow_back_white_24dp);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setResult(Activity.RESULT_OK);
                finish();
            }
        });
    }

    public void printBtn(View view) {
//        if (!StringUtils.isNullOrEmpty(realfee)){
//            ToastUtil.showSuccessToast(PayFeesActivity.this, "请先进行支付操作", ToastUtil.Position.TOP);return;
//        }
        print();

        getInvoceInfo();
    }

    public void printTickets(){
        new Thread() {
            public void run() {
                PrinterCtrl.powerOn();
                PrinterCtrl.PrintText("车牌号：" + carnum + "\n\n");
                PrinterCtrl.PrintText("车位号：" + carportCode + "\n\n");
                PrinterCtrl.PrintText("开始时间：" + starttime + "\n\n");
                PrinterCtrl.PrintText("结束时间："+endtime+ "\n\n");
                if (!StringUtils.isNullOrEmpty(realfee)){
                    PrinterCtrl.PrintText("金额："+realfee+ "\n\n");
                }else {
                    PrinterCtrl.PrintText("金额："+postageTxt.getText().toString() + "\n\n\n\n");
                }
                try {
                    sleep(1000);
                } catch (InterruptedException e) {
                }

            }

            ;
        }.start();
    }

    public void toPay(View view) {
        //获取费率
        new AlertDialogWrapper.Builder(this)
                .setTitle(getString(R.string.please_note))
                .setMessage("是否确认支付？")
                .setPositiveButton("确认", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        getPayConditionAndPay();
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                }).show();
    }

    public void getInvoceInfo(){
        SoapApi.getInvoceInfo(selectFormalOrder.getCode())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<GetInvoceInfoResponse>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        ToastUtil.showSuccessToast(PayFeesActivity.this, "上传票务失败", ToastUtil.Position.TOP);
                    }

                    @Override
                    public void onNext(GetInvoceInfoResponse getInvoceInfoResponse) {
                        if (getInvoceInfoResponse != null && getInvoceInfoResponse.getData() != null) {
                            GetInvoceInfoResponse.DataBean dataBean = getInvoceInfoResponse.getData().get(0);
                            endtime = dataBean.getEndtime();
                            printTickets();
                        } else {
                            ToastUtil.showSuccessToast(PayFeesActivity.this, "上传票务失败", ToastUtil.Position.TOP);
                        }
                    }
                });
    }

    public void print() {
        PrintRequest printRequest = new PrintRequest();
        printRequest.setEmployeeID(RealmManager.findUserInfo().getCode());
        printRequest.setAmount(realfee);
        printRequest.setPayType("1");
        printRequest.setRoadName(roadname);
        printRequest.setCarportCode(carportCode);
        printRequest.setCarNum(carnum);
        SoapApi.hmInsertInvoceInfo(printRequest)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<BaseResponse>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onNext(BaseResponse payFeesResponse) {
                        if (payFeesResponse != null && !TextUtils.isEmpty(payFeesResponse.getStatus())) {
                            if ("true".equals(payFeesResponse.getStatus())) {
                                ToastUtil.showSuccessToast(PayFeesActivity.this, "上传票务成功", ToastUtil.Position.TOP);
                                Intent intent = new Intent(PayFeesActivity.this, PaymentServiceActivity.class);
                                startActivity(intent);
                                finish();
                            } else {
                                if (!TextUtils.isEmpty(payFeesResponse.getMessage())) {
                                    ToastUtil.showSuccessToast(PayFeesActivity.this, payFeesResponse.getMessage(), ToastUtil.Position.TOP);
                                } else {
                                    ToastUtil.showSuccessToast(PayFeesActivity.this, "上传票务成功", ToastUtil.Position.TOP);
                                }
                            }
                        } else {
                            if (payFeesResponse != null && !TextUtils.isEmpty(payFeesResponse.getMessage())) {
                                ToastUtil.showSuccessToast(PayFeesActivity.this, payFeesResponse.getMessage(), ToastUtil.Position.TOP);
                            } else {
                                ToastUtil.showSuccessToast(PayFeesActivity.this, "上传票务失败", ToastUtil.Position.TOP);
                            }
                        }
                    }
                });
    }

    public void payFailState(){
        printBtn.setVisibility(View.GONE);
        payoffBtn.setVisibility(View.VISIBLE);
    }

    public void paySuccessState(){
        printBtn.setVisibility(View.VISIBLE);
        payoffBtn.setVisibility(View.GONE);
    }

    public void realpay() {
        SoapApi.hmParkingOut(orderId, realfee, RealmManager.findUserInfo().getCode(), payType)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<BaseResponse>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        payFailState();
                    }

                    @Override
                    public void onNext(BaseResponse payFeesResponse) {
                        if (payFeesResponse != null && !TextUtils.isEmpty(payFeesResponse.getStatus())) {
                            if ("true".equals(payFeesResponse.getStatus())) {
                                paySuccessState();
                                ToastUtil.showSuccessToast(PayFeesActivity.this, "支付成功已出场", ToastUtil.Position.TOP);
                                radio1.setEnabled(false);
                                radio3.setEnabled(false);
                            } else {
                                payFailState();
                                if (!TextUtils.isEmpty(payFeesResponse.getMessage())) {
                                    ToastUtil.showSuccessToast(PayFeesActivity.this, payFeesResponse.getMessage(), ToastUtil.Position.TOP);
                                } else {
                                    ToastUtil.showSuccessToast(PayFeesActivity.this, "支付失败未出场", ToastUtil.Position.TOP);
                                }
                            }
                        } else {
                            payFailState();
                            if (payFeesResponse != null && !TextUtils.isEmpty(payFeesResponse.getMessage())) {
                                ToastUtil.showSuccessToast(PayFeesActivity.this, payFeesResponse.getMessage(), ToastUtil.Position.TOP);
                            } else {
                                ToastUtil.showSuccessToast(PayFeesActivity.this, "支付失败", ToastUtil.Position.TOP);
                            }
                        }
                    }
                });
    }

    public void getPayConditionAndPay() {
        SoapApi.getHmPayCondition(orderId)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<PayFeesResponse>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        ToastUtil.showSuccessToast(PayFeesActivity.this, "获取费率失败", ToastUtil.Position.TOP);
                    }

                    @Override
                    public void onNext(PayFeesResponse payFeesResponse) {
                        if (payFeesResponse != null && !TextUtils.isEmpty(payFeesResponse.getStatus())) {
                            if ("true".equals(payFeesResponse.getStatus())) {
                                double fee = BussinessUtil.calculatePay(payFeesResponse.getData().get(0));
//                                postageTxt.setText(String.valueOf(fee));
                                realfee = String.valueOf(fee);
                                if (payType == 1) {//支付宝 打开扫描页面
                                    Intent intent = new Intent(PayFeesActivity.this, MipcaActivityCapture.class);
                                    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                                    startActivityForResult(intent, SCANNIN_GREQUEST_CODE);
                                } else {
                                    realpay();
                                }
//                                ToastUtil.showSuccessToast(PayFeesActivity.this, "获取费率成功", ToastUtil.Position.TOP);
                            } else {
                                if (!TextUtils.isEmpty(payFeesResponse.getMessage())) {
                                    ToastUtil.showSuccessToast(PayFeesActivity.this, payFeesResponse.getMessage(), ToastUtil.Position.TOP);
                                } else {
                                    ToastUtil.showSuccessToast(PayFeesActivity.this, "获取费率失败", ToastUtil.Position.TOP);
                                }
                            }
                        } else {
                            if (payFeesResponse != null && !TextUtils.isEmpty(payFeesResponse.getMessage())) {
                                ToastUtil.showSuccessToast(PayFeesActivity.this, payFeesResponse.getMessage(), ToastUtil.Position.TOP);
                            } else {
                                ToastUtil.showSuccessToast(PayFeesActivity.this, "获取费率失败", ToastUtil.Position.TOP);
                            }
                        }
                    }
                });
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case SCANNIN_GREQUEST_CODE:
                if(resultCode == RESULT_OK){
                    Bundle bundle = data.getExtras();
                   String text=bundle.getString("result");
                    alipyGetWay(text);
                }
                break;
        }
    }
    public void alipyGetWay(String authcode) {
        SoapApi.alipyGetWay(authcode,realfee,orderId)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<AlipayReqsponse>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        payFailState();
                        ToastUtil.showSuccessToast(PayFeesActivity.this, "支付失败", ToastUtil.Position.TOP);
                    }

                    @Override
                    public void onNext(AlipayReqsponse payFeesResponse) {
                        if (payFeesResponse != null && !TextUtils.isEmpty(payFeesResponse.getStatus())) {
                            if ("true".equals(payFeesResponse.getStatus())) {
                                paySuccessState();
                                ToastUtil.showSuccessToast(PayFeesActivity.this, "支付成功", ToastUtil.Position.TOP);
                            } else {
                                payFailState();
                                if (!TextUtils.isEmpty(payFeesResponse.getMessage())) {
                                    ToastUtil.showSuccessToast(PayFeesActivity.this, payFeesResponse.getMessage(), ToastUtil.Position.TOP);
                                } else {
                                    ToastUtil.showSuccessToast(PayFeesActivity.this, "支付失败", ToastUtil.Position.TOP);
                                }
                            }
                        } else {
                            payFailState();
                            if (payFeesResponse != null && !TextUtils.isEmpty(payFeesResponse.getMessage())) {
                                ToastUtil.showSuccessToast(PayFeesActivity.this, payFeesResponse.getMessage(), ToastUtil.Position.TOP);
                            } else {
                                ToastUtil.showSuccessToast(PayFeesActivity.this, "支付失败", ToastUtil.Position.TOP);
                            }
                        }
                    }
                });
    }
    String message="";

    public String getMessage(Rate rate) {
        if(StringUtils.isNullOrEmpty(message)&&"0".equals(rate.getMonday())){
            message="周一免费";
        }else  if((!StringUtils.isNullOrEmpty(message))&&"0".equals(rate.getMonday())){
            message=message+",周一免费";
        }
        if(StringUtils.isNullOrEmpty(message)&&"0".equals(rate.getTuesday())){
            message="周二免费";
        }else  if((!StringUtils.isNullOrEmpty(message))&&"0".equals(rate.getTuesday())){
            message=message+",周二免费";
        }
        if(StringUtils.isNullOrEmpty(message)&&"0".equals(rate.getWednesday())){
            message="周三免费";
        }else  if((!StringUtils.isNullOrEmpty(message))&&"0".equals(rate.getWednesday())){
            message=message+",周三免费";
        }
        if(StringUtils.isNullOrEmpty(message)&&"0".equals(rate.getThursday())){
            message="周四免费";
        }else  if((!StringUtils.isNullOrEmpty(message))&&"0".equals(rate.getThursday())){
            message=message+",周四免费";
        }
        if(StringUtils.isNullOrEmpty(message)&&"0".equals(rate.getFriday())){
            message="周五免费";
        }else  if((!StringUtils.isNullOrEmpty(message))&&"0".equals(rate.getFriday())){
            message=message+",周五免费";
        }
        if(StringUtils.isNullOrEmpty(message)&&"0".equals(rate.getSaturday())){
            message="周六免费";
        }else  if((!StringUtils.isNullOrEmpty(message))&&"0".equals(rate.getSaturday())){
            message=message+",周六免费";
        }
        if(StringUtils.isNullOrEmpty(message)&&"0".equals(rate.getSunday())){
            message="周日免费";
        }else  if((!StringUtils.isNullOrEmpty(message))&&"0".equals(rate.getSunday())){
            message=message+",周日免费";
        }
        return message;
    }
    public void getPayCondition() {
        SoapApi.getHmPayCondition(orderId)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<PayFeesResponse>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        ToastUtil.showSuccessToast(PayFeesActivity.this, "获取费率失败", ToastUtil.Position.TOP);
                    }

                    @Override
                    public void onNext(PayFeesResponse payFeesResponse) {
                        if (payFeesResponse != null && !TextUtils.isEmpty(payFeesResponse.getStatus())) {
                            if ("true".equals(payFeesResponse.getStatus())) {
                                message=getMessage(payFeesResponse.getData().get(0).getRateDetail());
                                pay_message.setText(message.toString());
                                double fee = BussinessUtil.calculatePay(payFeesResponse.getData().get(0));
                                postageTxt.setText(String.valueOf(fee)+"￥");
                                realfee = String.valueOf(fee);
//                                ToastUtil.showSuccessToast(PayFeesActivity.this, "获取费率成功", ToastUtil.Position.TOP);
                            } else {
                                if (!TextUtils.isEmpty(payFeesResponse.getMessage())) {
                                    ToastUtil.showSuccessToast(PayFeesActivity.this, payFeesResponse.getMessage(), ToastUtil.Position.TOP);
                                } else {
                                    ToastUtil.showSuccessToast(PayFeesActivity.this, "获取费率失败", ToastUtil.Position.TOP);
                                }
                            }
                        } else {
                            if (payFeesResponse != null && !TextUtils.isEmpty(payFeesResponse.getMessage())) {
                                ToastUtil.showSuccessToast(PayFeesActivity.this, payFeesResponse.getMessage(), ToastUtil.Position.TOP);
                            } else {
                                ToastUtil.showSuccessToast(PayFeesActivity.this, "获取费率失败", ToastUtil.Position.TOP);
                            }
                        }
                    }
                });
    }

}
